import React, { useEffect, useState } from "react";
import { SearchCityApi,geetCityApi } from "../../api/users";
import { useLoaderData, useNavigate, useSearchParams } from "react-router-dom";
import "./index.css";
import { NavBar, SearchBar, List,IndexBar } from "antd-mobile";
import { useDispatch } from "react-redux";
import { upLoadCity } from "../../store/slice/ticket";

function Index() {
  let nav = useNavigate();
  let dispacth = useDispatch();
  const [search] = useSearchParams();
  const loaderData = useLoaderData();
  const [wd, setWd] = useState("");
  let [list, setList] = useState([]);
  useEffect(() => {
    async function getSearch() {
      if (!wd) return;
      const { data: res } = await SearchCityApi(wd);
      console.log(res);
      setList(res.data);
    }
    getSearch();
  }, [wd]);
  const setCity = (city) => {
    const Obj = { type: search.get("type"), city };
    dispacth(upLoadCity(Obj));
    nav(-1);
  };
  const [citys,setCitys]=useState([])
  const getCity=async()=>{
    let {data:res}=await geetCityApi()
    console.log(res.data.cityList);
    
    setCitys(res.data.cityList)
  }
  useEffect(()=>{
    getCity()
  },[])
  return (
    <div className="box">
      <div className="search">
        <NavBar onBack={() => nav(-1)}>
          <SearchBar
            placeholder="请输入城市关键字"
            onChange={(val) => setWd(val)}
          ></SearchBar>
        </NavBar>
      </div>
      <List header="搜索结果">
        {list.map((item, i) => (
          <List.Item key={i} onClick={() => setCity(item.name)}>
            {item.name}
          </List.Item>
        ))}
      </List>

      <IndexBar>
        {citys.map(group => {
          const { title, items } = group
          return (
            <IndexBar.Panel
              index={title}
              title={`标题${title}`}
              key={`标题${title}`}
            >
              <List>
                {items&&items.map((item, index) => (
                  <List.Item key={index}>{item.name}</List.Item>
                ))}
              </List>
            </IndexBar.Panel>
          )
        })}
      </IndexBar>

    </div>
  );
}

export default Index;
